package cmd

import (
	"os"

	log "github.com/sirupsen/logrus"

	"github.com/asxjd/domainexpiry/collectors"
	"github.com/asxjd/domainexpiry/common"
	"github.com/spf13/cobra"
)

var (
	port    string
	config  string
	rootCmd = &cobra.Command{
		Use:   "dnsexpiry",
		Short: "asxjd dns expiry prometheus exporter",
		Long:  "监控DNS域名到期时间，直接运行命令dnsexpiry",
		PreRunE: func(cmd *cobra.Command, args []string) error {
			portBind()
			err := confFileIsExist()
			if err != nil {
				return err
			}
			return nil
		},
		RunE: func(cmd *cobra.Command, args []string) error {
			err := collectors.Srv()
			if err != nil {
				return err
			}
			return nil
		},
	}
)

func init() {
	rootCmd.PersistentFlags().StringVarP(&port, "port", "p", "9999", "程序监听端口，默认9999")
	rootCmd.PersistentFlags().StringVarP(&config, "config", "c", "/etc/dnsExpiry.yml", "默认配置文件")
}

func Execute() {
	if err := rootCmd.Execute(); err != nil {
		log.Panic(err)
	}
}

// confFileIsExist 判断是否指定配置文件或者默认文件是否存在
func confFileIsExist() error {
	log.Println("开始配置文件验证")
	if config == "" {
		_, err := os.Stat("/etc/dnsExpiry.yml")
		if err != nil {
			return err
		}
		common.Config = "/etc/dnsExpiry.yml"
	} else {
		_, err := os.Stat(config)
		if err != nil {
			return err
		}
		common.Config = config
	}
	log.Println("配置文件验证成功")
	return nil
}

func portBind() {
	if port == "" {
		common.Port = "9999"
	} else {
		common.Port = port
	}
}
